﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Routing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Collections.Specialized.BitVector32;

namespace IM.Easy.Core.Route
{
    public class RouteGenerator
    {
        /// <summary>
        /// 判断是否为api控制器
        /// </summary>
        /// <param name="controllerModel"></param>
        /// <returns></returns>
        public bool IsApi(ControllerModel controllerModel)
        {
            //var apiController = controllerModel.Attributes.OfType<ApiExplorerAttribute>().FirstOrDefault();
            var apiController = controllerModel.Attributes.OfType<ApiIgnoreAttribute>().FirstOrDefault();
            return apiController == null;
        }

        /// <summary>
        /// 判断是否需要生成route的action
        /// </summary>
        /// <returns></returns>
        public bool IsRoute(ActionModel action)
        {
            var ignore = action.Attributes.OfType<ApiIgnoreAttribute>().FirstOrDefault();
            return ignore == null;
        }

        /// <summary>
        /// 处理控制器路由，添加 "/api" 前缀。
        /// </summary>
        /// <param name="controllerModel">控制器模型</param>
        public void ProcessControllerRoutes(ControllerModel controllerModel)
        {
            foreach (var selector in controllerModel.Selectors)
            {
                // 如果路由模板存在
                if (selector.AttributeRouteModel != null)
                {
                    var routeTemplate = selector.AttributeRouteModel.Template;

                    // 如果路由不以 "api" 开头，则添加前缀
                    if (!routeTemplate.StartsWith(RoutePrefix.Prefix, StringComparison.OrdinalIgnoreCase))
                    {
                        selector.AttributeRouteModel.Template = RoutePrefix.AddApiPrefix(routeTemplate);
                    }
                }
                else
                {
                    // 如果没有路由特性，设置默认的 "api/{controller}"
                    selector.AttributeRouteModel = new AttributeRouteModel(
                        new RouteAttribute($"{RoutePrefix.Prefix}/{controllerModel.ControllerName}"));
                }
            }
        }

        public void ProcessActionRoutes(ActionModel action)
        {

            var httpMethodAttribute = action.Attributes.OfType<HttpMethodAttribute>().FirstOrDefault();
            var actionName = action.ActionName;
            if (httpMethodAttribute == null)
            {
                // 如果没有 HTTP 动作特性，则根据方法名称生成路由
                var httpMethod = actionName.StartsWith("Get") ? "GET" :
                                  actionName.StartsWith("Post") || actionName.StartsWith("Add") || actionName.StartsWith("Create") ? "POST" :
                                  actionName.StartsWith("Put") || actionName.StartsWith("Update") ? "PUT" :
                                  actionName.StartsWith("Delete") ? "DELETE" :
                                  "GET"; // 默认使用 GET
                var routeTemplate = RoutePrefix.RemoveHttpPrefix(actionName).ToLower();
                action.Selectors[0].AttributeRouteModel = new AttributeRouteModel(new RouteAttribute(routeTemplate));
                // 设置 HTTP 方法
                action.Selectors[0].ActionConstraints.Add(new HttpMethodActionConstraint([httpMethod]));
            }
            else
            {
                // 如果方法上已有 HTTP 动作特性，则使用特性的模板
                var routeTemplate = httpMethodAttribute.Template;
                if (string.IsNullOrEmpty(routeTemplate))
                {
                    // 如果 routeTemplate 为 null 或空，使用默认路由模板
                    routeTemplate = RoutePrefix.RemoveHttpPrefix(actionName).ToLower();
                }
                action.Selectors[0].AttributeRouteModel = new AttributeRouteModel(new RouteAttribute(routeTemplate));
            }
        }
    }
}
